# 创建商家设置页面
<template>
  <div class="settings">
    <el-tabs v-model="activeTab">
      <!-- 基础配置 -->
      <el-tab-pane label="基础配置" name="basic">
        <el-form
          ref="basicFormRef"
          :model="basicForm"
          :rules="basicFormRules"
          label-width="120px"
        >
          <el-form-item label="商家名称" prop="name">
            <el-input v-model="basicForm.name" placeholder="请输入商家名称" />
          </el-form-item>
          <el-form-item label="商家简介" prop="description">
            <el-input
              v-model="basicForm.description"
              type="textarea"
              :rows="3"
              placeholder="请输入商家简介"
            />
          </el-form-item>
          <el-form-item label="联系电话" prop="phone">
            <el-input v-model="basicForm.phone" placeholder="请输入联系电话" />
          </el-form-item>
          <el-form-item label="营业时间" prop="businessHours">
            <el-time-picker
              v-model="basicForm.openTime"
              placeholder="开始时间"
              format="HH:mm"
            />
            <span class="mx-2">至</span>
            <el-time-picker
              v-model="basicForm.closeTime"
              placeholder="结束时间"
              format="HH:mm"
            />
          </el-form-item>
          <el-form-item label="商家地址" prop="address">
            <el-input v-model="basicForm.address" placeholder="请输入商家地址" />
          </el-form-item>
          <el-form-item label="商家Logo" prop="logo">
            <el-upload
              class="avatar-uploader"
              :action="uploadUrl"
              :show-file-list="false"
              :on-success="handleLogoSuccess"
              :before-upload="beforeLogoUpload"
            >
              <img v-if="basicForm.logo" :src="basicForm.logo" class="avatar" />
              <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
            </el-upload>
          </el-form-item>
          <el-form-item label="商家图片" prop="images">
            <el-upload
              :action="uploadUrl"
              list-type="picture-card"
              :on-success="handleImageSuccess"
              :before-upload="beforeImageUpload"
            >
              <el-icon><Plus /></el-icon>
            </el-upload>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleBasicSubmit">保存</el-button>
          </el-form-item>
        </el-form>
      </el-tab-pane>

      <!-- 通知配置 -->
      <el-tab-pane label="通知配置" name="notification">
        <el-form
          ref="notificationFormRef"
          :model="notificationForm"
          label-width="120px"
        >
          <el-form-item label="订单通知">
            <el-switch
              v-model="notificationForm.orderNotification"
              active-text="开启"
              inactive-text="关闭"
            />
          </el-form-item>
          <el-form-item label="通知方式">
            <el-checkbox-group v-model="notificationForm.notificationMethods">
              <el-checkbox label="sms">短信</el-checkbox>
              <el-checkbox label="email">邮件</el-checkbox>
              <el-checkbox label="wechat">微信</el-checkbox>
            </el-checkbox-group>
          </el-form-item>
          <el-form-item label="通知模板">
            <el-select v-model="notificationForm.template" placeholder="请选择通知模板">
              <el-option label="模板一" value="template1" />
              <el-option label="模板二" value="template2" />
              <el-option label="模板三" value="template3" />
            </el-select>
          </el-form-item>
          <el-form-item label="通知时间">
            <el-time-picker
              v-model="notificationForm.notificationTime"
              placeholder="选择时间"
              format="HH:mm"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleNotificationSubmit">保存</el-button>
          </el-form-item>
        </el-form>
      </el-tab-pane>

      <!-- 备份与恢复 -->
      <el-tab-pane label="备份与恢复" name="backup">
        <div class="backup-section">
          <h3>数据备份</h3>
          <el-form :model="backupForm" label-width="120px">
            <el-form-item label="备份类型">
              <el-select v-model="backupForm.type" placeholder="请选择备份类型">
                <el-option label="完整备份" value="full" />
                <el-option label="增量备份" value="incremental" />
              </el-select>
            </el-form-item>
            <el-form-item label="备份周期">
              <el-select v-model="backupForm.cycle" placeholder="请选择备份周期">
                <el-option label="每天" value="daily" />
                <el-option label="每周" value="weekly" />
                <el-option label="每月" value="monthly" />
              </el-select>
            </el-form-item>
            <el-form-item label="备份时间">
              <el-time-picker
                v-model="backupForm.time"
                placeholder="选择时间"
                format="HH:mm"
              />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleBackup">立即备份</el-button>
              <el-button @click="handleBackupSchedule">设置定时备份</el-button>
            </el-form-item>
          </el-form>
        </div>

        <div class="backup-section">
          <h3>备份记录</h3>
          <el-table :data="backupList" style="width: 100%">
            <el-table-column prop="time" label="备份时间" width="180" />
            <el-table-column prop="type" label="备份类型" width="120" />
            <el-table-column prop="size" label="文件大小" width="120" />
            <el-table-column prop="status" label="状态" width="120">
              <template #default="{ row }">
                <el-tag :type="row.status === 'success' ? 'success' : 'danger'">
                  {{ row.status === 'success' ? '成功' : '失败' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作">
              <template #default="{ row }">
                <el-button type="primary" link @click="handleRestore(row)">
                  恢复
                </el-button>
                <el-button type="primary" link @click="handleDownload(row)">
                  下载
                </el-button>
                <el-button type="danger" link @click="handleDeleteBackup(row)">
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-tab-pane>

      <!-- 智能推荐 -->
      <el-tab-pane label="智能推荐" name="recommendation">
        <el-form
          ref="recommendationFormRef"
          :model="recommendationForm"
          label-width="120px"
        >
          <el-form-item label="推荐开关">
            <el-switch
              v-model="recommendationForm.enabled"
              active-text="开启"
              inactive-text="关闭"
            />
          </el-form-item>
          <el-form-item label="推荐类型">
            <el-checkbox-group v-model="recommendationForm.types">
              <el-checkbox label="product">商品推荐</el-checkbox>
              <el-checkbox label="service">服务推荐</el-checkbox>
              <el-checkbox label="promotion">促销推荐</el-checkbox>
            </el-checkbox-group>
          </el-form-item>
          <el-form-item label="推荐算法">
            <el-select v-model="recommendationForm.algorithm" placeholder="请选择推荐算法">
              <el-option label="协同过滤" value="collaborative" />
              <el-option label="内容推荐" value="content" />
              <el-option label="热门推荐" value="popular" />
            </el-select>
          </el-form-item>
          <el-form-item label="推荐数量">
            <el-input-number
              v-model="recommendationForm.count"
              :min="1"
              :max="20"
            />
          </el-form-item>
          <el-form-item label="更新频率">
            <el-select v-model="recommendationForm.frequency" placeholder="请选择更新频率">
              <el-option label="实时" value="realtime" />
              <el-option label="每小时" value="hourly" />
              <el-option label="每天" value="daily" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleRecommendationSubmit">保存</el-button>
            <el-button @click="handleRecommendationTest">测试推荐</el-button>
          </el-form-item>
        </el-form>

        <div class="recommendation-preview">
          <h3>推荐效果预览</h3>
          <el-table :data="recommendationPreview" style="width: 100%">
            <el-table-column prop="name" label="推荐项" />
            <el-table-column prop="type" label="类型" width="120" />
            <el-table-column prop="score" label="推荐分数" width="120" />
            <el-table-column prop="reason" label="推荐理由" />
          </el-table>
        </div>
      </el-tab-pane>

      <!-- 税务管理 -->
      <el-tab-pane label="税务管理" name="tax">
        <el-form
          ref="taxFormRef"
          :model="taxForm"
          :rules="taxFormRules"
          label-width="120px"
        >
          <el-form-item label="纳税人类型" prop="type">
            <el-select v-model="taxForm.type" placeholder="请选择纳税人类型">
              <el-option label="一般纳税人" value="general" />
              <el-option label="小规模纳税人" value="small" />
            </el-select>
          </el-form-item>
          <el-form-item label="纳税人识别号" prop="taxNumber">
            <el-input v-model="taxForm.taxNumber" placeholder="请输入纳税人识别号" />
          </el-form-item>
          <el-form-item label="税务登记证" prop="taxCertificate">
            <el-upload
              class="upload-demo"
              :action="uploadUrl"
              :on-success="handleTaxCertificateSuccess"
              :before-upload="beforeTaxCertificateUpload"
            >
              <el-button type="primary">上传税务登记证</el-button>
            </el-upload>
          </el-form-item>
          <el-form-item label="开票信息" prop="invoiceInfo">
            <el-input
              v-model="taxForm.invoiceInfo"
              type="textarea"
              :rows="3"
              placeholder="请输入开票信息"
            />
          </el-form-item>
          <el-form-item label="税率设置">
            <el-table :data="taxForm.rates" style="width: 100%">
              <el-table-column prop="name" label="税目" />
              <el-table-column prop="rate" label="税率">
                <template #default="{ row }">
                  <el-input-number
                    v-model="row.rate"
                    :min="0"
                    :max="100"
                    :precision="2"
                    :step="0.1"
                  />
                </template>
              </el-table-column>
              <el-table-column label="操作" width="120">
                <template #default="{ $index }">
                  <el-button
                    type="danger"
                    link
                    @click="handleDeleteTaxRate($index)"
                  >
                    删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
            <div class="mt-2">
              <el-button type="primary" @click="handleAddTaxRate">添加税率</el-button>
            </div>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleTaxSubmit">保存</el-button>
          </el-form-item>
        </el-form>

        <div class="tax-statistics">
          <h3>税务统计</h3>
          <el-row :gutter="20">
            <el-col :span="8">
              <el-card shadow="hover">
                <template #header>
                  <div class="card-header">
                    <span>本月税额</span>
                  </div>
                </template>
                <div class="card-content">
                  <div class="amount">¥{{ formatNumber(taxStatistics.monthlyTax) }}</div>
                </div>
              </el-card>
            </el-col>
            <el-col :span="8">
              <el-card shadow="hover">
                <template #header>
                  <div class="card-header">
                    <span>本年税额</span>
                  </div>
                </template>
                <div class="card-content">
                  <div class="amount">¥{{ formatNumber(taxStatistics.yearlyTax) }}</div>
                </div>
              </el-card>
            </el-col>
            <el-col :span="8">
              <el-card shadow="hover">
                <template #header>
                  <div class="card-header">
                    <span>待缴税额</span>
                  </div>
                </template>
                <div class="card-content">
                  <div class="amount">¥{{ formatNumber(taxStatistics.pendingTax) }}</div>
                </div>
              </el-card>
            </el-col>
          </el-row>
        </div>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import {
  getMerchantSettings,
  updateMerchantSettings,
  getMerchantNotificationSettings,
  updateMerchantNotificationSettings,
  getMerchantBackupList,
  createMerchantBackup,
  restoreMerchantBackup,
  deleteMerchantBackup,
  getMerchantRecommendationSettings,
  updateMerchantRecommendationSettings,
  testMerchantRecommendation,
  getMerchantTaxSettings,
  updateMerchantTaxSettings,
  getMerchantTaxStatistics
} from '@/api/merchant'

// 当前激活的标签页
const activeTab = ref('basic')

// 上传地址
const uploadUrl = '/api/merchant/upload'

// 基础配置表单
const basicFormRef = ref(null)
const basicForm = reactive({
  name: '',
  description: '',
  phone: '',
  openTime: '',
  closeTime: '',
  address: '',
  logo: '',
  images: []
})

// 基础配置表单验证规则
const basicFormRules = {
  name: [{ required: true, message: '请输入商家名称', trigger: 'blur' }],
  phone: [{ required: true, message: '请输入联系电话', trigger: 'blur' }],
  address: [{ required: true, message: '请输入商家地址', trigger: 'blur' }]
}

// 通知配置表单
const notificationFormRef = ref(null)
const notificationForm = reactive({
  orderNotification: true,
  notificationMethods: ['sms', 'email'],
  template: 'template1',
  notificationTime: ''
})

// 备份表单
const backupForm = reactive({
  type: 'full',
  cycle: 'daily',
  time: ''
})

// 备份列表
const backupList = ref([])

// 智能推荐表单
const recommendationFormRef = ref(null)
const recommendationForm = reactive({
  enabled: true,
  types: ['product', 'service'],
  algorithm: 'collaborative',
  count: 10,
  frequency: 'daily'
})

// 推荐预览数据
const recommendationPreview = ref([])

// 税务表单
const taxFormRef = ref(null)
const taxForm = reactive({
  type: 'general',
  taxNumber: '',
  taxCertificate: '',
  invoiceInfo: '',
  rates: []
})

// 税务表单验证规则
const taxFormRules = {
  type: [{ required: true, message: '请选择纳税人类型', trigger: 'change' }],
  taxNumber: [{ required: true, message: '请输入纳税人识别号', trigger: 'blur' }],
  taxCertificate: [{ required: true, message: '请上传税务登记证', trigger: 'change' }]
}

// 税务统计数据
const taxStatistics = reactive({
  monthlyTax: 0,
  yearlyTax: 0,
  pendingTax: 0
})

// 获取基础配置
const getBasicSettings = async () => {
  try {
    const { data } = await getMerchantSettings()
    Object.assign(basicForm, data)
  } catch (error) {
    console.error('获取基础配置失败:', error)
    ElMessage.error('获取基础配置失败')
  }
}

// 提交基础配置
const handleBasicSubmit = async () => {
  if (!basicFormRef.value) return
  
  try {
    await basicFormRef.value.validate()
    await updateMerchantSettings(basicForm)
    ElMessage.success('保存成功')
  } catch (error) {
    console.error('保存基础配置失败:', error)
  }
}

// 获取通知配置
const getNotificationSettings = async () => {
  try {
    const { data } = await getMerchantNotificationSettings()
    Object.assign(notificationForm, data)
  } catch (error) {
    console.error('获取通知配置失败:', error)
    ElMessage.error('获取通知配置失败')
  }
}

// 提交通知配置
const handleNotificationSubmit = async () => {
  try {
    await updateMerchantNotificationSettings(notificationForm)
    ElMessage.success('保存成功')
  } catch (error) {
    console.error('保存通知配置失败:', error)
  }
}

// 获取备份列表
const getBackupList = async () => {
  try {
    const { data } = await getMerchantBackupList()
    backupList.value = data
  } catch (error) {
    console.error('获取备份列表失败:', error)
    ElMessage.error('获取备份列表失败')
  }
}

// 创建备份
const handleBackup = async () => {
  try {
    await createMerchantBackup(backupForm)
    ElMessage.success('备份成功')
    getBackupList()
  } catch (error) {
    console.error('创建备份失败:', error)
    ElMessage.error('创建备份失败')
  }
}

// 设置定时备份
const handleBackupSchedule = async () => {
  try {
    await updateMerchantSettings({ backup: backupForm })
    ElMessage.success('设置成功')
  } catch (error) {
    console.error('设置定时备份失败:', error)
    ElMessage.error('设置定时备份失败')
  }
}

// 恢复备份
const handleRestore = async (row) => {
  try {
    await ElMessageBox.confirm('确认要恢复该备份吗？', '提示', {
      type: 'warning'
    })
    await restoreMerchantBackup(row.id)
    ElMessage.success('恢复成功')
  } catch (error) {
    if (error !== 'cancel') {
      console.error('恢复备份失败:', error)
      ElMessage.error('恢复备份失败')
    }
  }
}

// 删除备份
const handleDeleteBackup = async (row) => {
  try {
    await ElMessageBox.confirm('确认要删除该备份吗？', '提示', {
      type: 'warning'
    })
    await deleteMerchantBackup(row.id)
    ElMessage.success('删除成功')
    getBackupList()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除备份失败:', error)
      ElMessage.error('删除备份失败')
    }
  }
}

// 下载备份
const handleDownload = (row) => {
  window.open(`/api/merchant/backup/${row.id}/download`)
}

// 获取推荐设置
const getRecommendationSettings = async () => {
  try {
    const { data } = await getMerchantRecommendationSettings()
    Object.assign(recommendationForm, data)
  } catch (error) {
    console.error('获取推荐设置失败:', error)
    ElMessage.error('获取推荐设置失败')
  }
}

// 提交推荐设置
const handleRecommendationSubmit = async () => {
  try {
    await updateMerchantRecommendationSettings(recommendationForm)
    ElMessage.success('保存成功')
  } catch (error) {
    console.error('保存推荐设置失败:', error)
  }
}

// 测试推荐
const handleRecommendationTest = async () => {
  try {
    const { data } = await testMerchantRecommendation(recommendationForm)
    recommendationPreview.value = data
  } catch (error) {
    console.error('测试推荐失败:', error)
    ElMessage.error('测试推荐失败')
  }
}

// 获取税务设置
const getTaxSettings = async () => {
  try {
    const { data } = await getMerchantTaxSettings()
    Object.assign(taxForm, data)
  } catch (error) {
    console.error('获取税务设置失败:', error)
    ElMessage.error('获取税务设置失败')
  }
}

// 提交税务设置
const handleTaxSubmit = async () => {
  if (!taxFormRef.value) return
  
  try {
    await taxFormRef.value.validate()
    await updateMerchantTaxSettings(taxForm)
    ElMessage.success('保存成功')
  } catch (error) {
    console.error('保存税务设置失败:', error)
  }
}

// 添加税率
const handleAddTaxRate = () => {
  taxForm.rates.push({
    name: '',
    rate: 0
  })
}

// 删除税率
const handleDeleteTaxRate = (index) => {
  taxForm.rates.splice(index, 1)
}

// 获取税务统计
const getTaxStatistics = async () => {
  try {
    const { data } = await getMerchantTaxStatistics()
    Object.assign(taxStatistics, data)
  } catch (error) {
    console.error('获取税务统计失败:', error)
    ElMessage.error('获取税务统计失败')
  }
}

// Logo上传成功
const handleLogoSuccess = (response) => {
  basicForm.logo = response.url
}

// Logo上传前校验
const beforeLogoUpload = (file) => {
  const isImage = file.type.startsWith('image/')
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isImage) {
    ElMessage.error('只能上传图片文件!')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过 2MB!')
    return false
  }
  return true
}

// 图片上传成功
const handleImageSuccess = (response) => {
  basicForm.images.push(response.url)
}

// 图片上传前校验
const beforeImageUpload = (file) => {
  const isImage = file.type.startsWith('image/')
  const isLt5M = file.size / 1024 / 1024 < 5

  if (!isImage) {
    ElMessage.error('只能上传图片文件!')
    return false
  }
  if (!isLt5M) {
    ElMessage.error('图片大小不能超过 5MB!')
    return false
  }
  return true
}

// 税务登记证上传成功
const handleTaxCertificateSuccess = (response) => {
  taxForm.taxCertificate = response.url
}

// 税务登记证上传前校验
const beforeTaxCertificateUpload = (file) => {
  const isPDF = file.type === 'application/pdf'
  const isLt10M = file.size / 1024 / 1024 < 10

  if (!isPDF) {
    ElMessage.error('只能上传PDF文件!')
    return false
  }
  if (!isLt10M) {
    ElMessage.error('文件大小不能超过 10MB!')
    return false
  }
  return true
}

// 格式化数字
const formatNumber = (num) => {
  return num.toLocaleString('zh-CN', {
    minimumFractionDigits: 2,
    maximumFractionDigits: 2
  })
}

onMounted(() => {
  getBasicSettings()
  getNotificationSettings()
  getBackupList()
  getRecommendationSettings()
  getTaxSettings()
  getTaxStatistics()
})
</script>

<style lang="scss" scoped>
.settings {
  padding: 20px;

  .backup-section {
    margin-bottom: 30px;

    h3 {
      margin-bottom: 20px;
      font-weight: normal;
      color: #606266;
    }
  }

  .recommendation-preview {
    margin-top: 30px;

    h3 {
      margin-bottom: 20px;
      font-weight: normal;
      color: #606266;
    }
  }

  .tax-statistics {
    margin-top: 30px;

    h3 {
      margin-bottom: 20px;
      font-weight: normal;
      color: #606266;
    }

    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
    }

    .card-content {
      text-align: center;

      .amount {
        font-size: 24px;
        font-weight: bold;
        color: #303133;
      }
    }
  }

  .avatar-uploader {
    :deep(.el-upload) {
      border: 1px dashed #d9d9d9;
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
      transition: var(--el-transition-duration-fast);

      &:hover {
        border-color: var(--el-color-primary);
      }
    }
  }

  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 100px;
    height: 100px;
    text-align: center;
    line-height: 100px;
  }

  .avatar {
    width: 100px;
    height: 100px;
    display: block;
  }

  .mx-2 {
    margin: 0 8px;
  }

  .mt-2 {
    margin-top: 8px;
  }
}
</style> 